package ch.headshot.photomap.client.editor.control;

import ch.headshot.photomap.client.editor.view.GpxStructure;
import ch.headshot.photomap.client.gpx.Gpx;
import ch.headshot.photomap.client.gpx.impl.GpxImpl;

import com.google.gwt.core.client.GWT;
import com.google.gwt.http.client.Request;
import com.google.gwt.http.client.RequestBuilder;
import com.google.gwt.http.client.RequestCallback;
import com.google.gwt.http.client.RequestException;
import com.google.gwt.http.client.Response;
import com.google.gwt.http.client.URL;
import com.google.gwt.user.client.Command;
import com.google.gwt.user.client.Window;
import com.google.gwt.xml.client.XMLParser;

public class LoadGpxCommand implements Command {

	public void execute() {
		String prompt = Window.prompt("Enter the url of the gpx File", "rhoneWanderung.xml");
		if (prompt == null || prompt.length() == 0) {
			return;
		}
		readGPX(prompt);
	}

	private void readGPX(final String url) {

		RequestBuilder builder = new RequestBuilder(RequestBuilder.GET, URL.encode(url));

		try {
			Request request = builder.sendRequest(null, new RequestCallback() {

				public void onError(Request request, Throwable exception) {
					GWT.log("faild to read gpx", exception);
					Window.alert("failed to read gpx " + url);
				}

				public void onResponseReceived(Request request, Response response) {
					if (200 != response.getStatusCode()) {
						GWT.log("faild to read gpx: " + response.getStatusText(), null);
						Window.alert("failed to read gpx " + url);
					} else {

						Gpx gpx = new GpxImpl(XMLParser.parse(response.getText()).getDocumentElement());
						GpxStructure.getInstance().setGpx(gpx);
					}
				}

			});
		} catch (RequestException e) {
			GWT.log("faild to read gpx", e);
			Window.alert("failed to read gpx " + url);
		}

	}

}
